const { classApi } = require('../../../utils/api');
const auth = require('../../../utils/auth');

Page({
  data: {
    // 表单数据
    formData: {
      className: '',
      grade: '',
      subject: '',
      description: '',
      maxStudents: 50,
      isPublic: true,
      allowJoin: true
    },
    // 选择器索引
    gradeIndex: -1,
    subjectIndex: -1,
    // 选中的标签
    selectedGradeLabel: '',
    selectedSubjectLabel: '',
    // 年级选项
    gradeOptions: [
      { value: '1', label: '一年级' },
      { value: '2', label: '二年级' },
      { value: '3', label: '三年级' },
      { value: '4', label: '四年级' },
      { value: '5', label: '五年级' },
      { value: '6', label: '六年级' },
      { value: '7', label: '七年级' },
      { value: '8', label: '八年级' },
      { value: '9', label: '九年级' },
      { value: '10', label: '高一' },
      { value: '11', label: '高二' },
      { value: '12', label: '高三' }
    ],
    // 学科选项
    subjectOptions: [
      { value: 'chinese', label: '语文' },
      { value: 'math', label: '数学' },
      { value: 'english', label: '英语' },
      { value: 'physics', label: '物理' },
      { value: 'chemistry', label: '化学' },
      { value: 'biology', label: '生物' },
      { value: 'history', label: '历史' },
      { value: 'geography', label: '地理' },
      { value: 'politics', label: '政治' },
      { value: 'other', label: '其他' }
    ],
    // 页面状态
    loading: false,
    submitting: false
  },

  onLoad(options) {
    console.log('新建班级页面加载');
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    if (!auth.isLoggedIn()) {
      console.log('用户未登录，跳转到登录页');
      auth.goToLogin();
      return;
    }
    
    const userInfo = auth.getUserInfo();
    console.log('用户已登录:', userInfo);
  },

  // 班级名称输入
  onClassNameInput(e) {
    this.setData({
      'formData.className': e.detail.value
    });
  },

  // 年级选择
  onGradeChange(e) {
    const index = parseInt(e.detail.value);
    const selectedGrade = this.data.gradeOptions[index];
    this.setData({
      gradeIndex: index,
      selectedGradeLabel: selectedGrade.label,
      'formData.grade': selectedGrade.value
    });
  },

  // 学科选择
  onSubjectChange(e) {
    const index = parseInt(e.detail.value);
    const selectedSubject = this.data.subjectOptions[index];
    this.setData({
      subjectIndex: index,
      selectedSubjectLabel: selectedSubject.label,
      'formData.subject': selectedSubject.value
    });
  },

  // 班级描述输入
  onDescriptionInput(e) {
    this.setData({
      'formData.description': e.detail.value
    });
  },

  // 最大学生数输入
  onMaxStudentsInput(e) {
    this.setData({
      'formData.maxStudents': parseInt(e.detail.value) || 50
    });
  },

  // 是否公开切换
  onPublicChange(e) {
    this.setData({
      'formData.isPublic': e.detail.value
    });
  },

  // 是否允许加入切换
  onAllowJoinChange(e) {
    this.setData({
      'formData.allowJoin': e.detail.value
    });
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data;
    
    if (!formData.className.trim()) {
      wx.showToast({
        title: '请输入班级名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.grade) {
      wx.showToast({
        title: '请选择年级',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.subject) {
      wx.showToast({
        title: '请选择学科',
        icon: 'none'
      });
      return false;
    }
    
    if (formData.maxStudents < 1 || formData.maxStudents > 200) {
      wx.showToast({
        title: '学生数量应在1-200之间',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  },

  // 提交表单
  async onSubmit() {
    if (!this.validateForm()) {
      return;
    }
    
    this.setData({ submitting: true });
    
    try {
      console.log('提交班级数据:', this.data.formData);
      
      // 获取当前用户信息
      const userInfo = auth.getUserInfo();
      if (!userInfo || !userInfo.id) {
        throw new Error('用户信息不完整，请重新登录');
      }
      
      // 构建提交数据
      const submitData = {
        ...this.data.formData,
        creatorUserId: userInfo.id,
        creatorName: userInfo.nickname || userInfo.name,
        createTime: new Date().toISOString()
      };
      
      console.log('提交到API的数据:', submitData);
      
      // 调用API创建班级
      const result = await classApi.addClass(submitData);
      console.log('班级创建成功:', result);
      
      wx.showToast({
        title: '班级创建成功',
        icon: 'success',
        duration: 2000
      });
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        wx.navigateBack({
          success: () => {
            // 通知上一页刷新数据
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.loadClassList) {
              prevPage.loadClassList();
            }
          }
        });
      }, 2000);
      
    } catch (error) {
      console.error('创建班级失败:', error);
      
      let errorMessage = '创建班级失败';
      if (error.message) {
        errorMessage = error.message;
      }
      
      wx.showModal({
        title: '创建失败',
        content: errorMessage,
        showCancel: false
      });
      
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 重置表单
  onReset() {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置表单吗？所有输入的内容将被清空。',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            formData: {
              className: '',
              grade: '',
              subject: '',
              description: '',
              maxStudents: 50,
              isPublic: true,
              allowJoin: true
            },
            gradeIndex: -1,
            subjectIndex: -1,
            selectedGradeLabel: '',
            selectedSubjectLabel: ''
          });
          
          wx.showToast({
            title: '表单已重置',
            icon: 'success'
          });
        }
      }
    });
  },

  // 预览班级信息
  onPreview() {
    const { formData } = this.data;
    
    let previewText = `班级名称：${formData.className || '未填写'}\n`;
    previewText += `年级：${this.getGradeLabel(formData.grade)}\n`;
    previewText += `学科：${this.getSubjectLabel(formData.subject)}\n`;
    previewText += `最大学生数：${formData.maxStudents}\n`;
    previewText += `是否公开：${formData.isPublic ? '是' : '否'}\n`;
    previewText += `允许加入：${formData.allowJoin ? '是' : '否'}\n`;
    previewText += `班级描述：${formData.description || '无'}`;
    
    wx.showModal({
      title: '班级信息预览',
      content: previewText,
      showCancel: false
    });
  },

  // 获取年级标签
  getGradeLabel(value) {
    const option = this.data.gradeOptions.find(item => item.value === value);
    return option ? option.label : '未选择';
  },

  // 获取学科标签
  getSubjectLabel(value) {
    const option = this.data.subjectOptions.find(item => item.value === value);
    return option ? option.label : '未选择';
  }
});

